package com.jevons.muffin.widget.alertView;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;


import com.jevons.muffin.R;
import com.jevons.muffin.adapter.BaseAdapter;
import com.jevons.muffin.adapter.ViewHolder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * @author linaisheng
 * Created at 2019/3/21.
 */

public class AlertView extends Dialog {

    //AlertView样式
    public enum Style {
        Dialog,         //普通弹框
        ActionSheet     //底部弹框
    }

    //Dialog样式下多条目样式
    private enum ItemsType {
        Null,
        Items,          //普通列表
        SingleChoice,   //单选
        MultiChoice     //多选
    }


    private LinearLayout llRoot;

    //标题
    private TextView tvTitle;
    //内容
    private TextView tvMessage;
    //列表
    private ListView lvItems;
    //底部分割线
    private View bottomDivider;
    //底部按钮
    private LinearLayout llBottomBtn;
    //提交
    private TextView btnConfirm;
    //取消
    private TextView btnCancel;
    //提交与取消中间的分割线
    private View centerDivider;
    //底部弹框取消按钮
    private TextView sheetCancel;

    //标题
    private String title;
    //内容
    private String message;
    //确定文字
    private String confirmTxt;
    //取消文字
    private String cancelTxt;

    //确定点击监听
    private OnClickListener confirmListener;
    //取消点击监听
    private OnClickListener cancelListener;

    private Builder builder;

    private AlertView(@NonNull Context context, @NonNull Builder builder) {
        super(context);
        this.builder = builder;
        this.title = builder.mTitle;
        this.message = builder.mMessage;
        this.confirmTxt = builder.mConfirmText;
        this.cancelTxt = builder.mCancelText;
        this.confirmListener = builder.onConfirmListener;
        this.cancelListener = builder.onCancelListener;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (builder.alertStyle == Style.Dialog) {
            setContentView(R.layout.dialog_alert_view_layout);
            initDialogView();
        } else {
            setContentView(R.layout.dialog_action_sheet_layout);
            initSheetView();
            Window dialogWindow = this.getWindow(); //得到对话框
            dialogWindow.setWindowAnimations(R.style.AlertSheetAnim);
            dialogWindow.setGravity(Gravity.BOTTOM);
            dialogWindow.setBackgroundDrawable(getContext()
                    .getResources().getDrawable(R.drawable.bg_action_sheet_window));
//            dialogWindow.setBackgroundDrawable(null);
        }
    }

    //初始化普通弹框
    private void initDialogView() {
        llRoot = (LinearLayout) findViewById(R.id.ll_dialog_root);

        tvTitle = (TextView) findViewById(R.id.tv_title);

        tvMessage = (TextView) findViewById(R.id.tv_message);
        lvItems = (ListView) findViewById(R.id.lv_items);

        bottomDivider = findViewById(R.id.view_bottom_divider);

        llBottomBtn = (LinearLayout) findViewById(R.id.ll_bottom_btn);
        btnConfirm = (TextView) findViewById(R.id.btn_confirm);
        btnCancel = (TextView) findViewById(R.id.btn_cancel);
        centerDivider = findViewById(R.id.view_center_divider);

        //判断是否显示标题
        if (!TextUtils.isEmpty(title)) {
            tvTitle.setText(title);
        } else {
            tvTitle.setVisibility(View.GONE);
        }

        //列表样式
        if (builder.itemsType == ItemsType.Items) {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) llRoot.getLayoutParams();
            params.width = RelativeLayout.LayoutParams.MATCH_PARENT;
            llRoot.setLayoutParams(params);

            lvItems.setVisibility(View.VISIBLE);
            if (builder.listAdapter == null) {
                lvItems.setAdapter(new ArrayAdapter<>(getContext(),
                        android.R.layout.simple_list_item_1,
                        builder.textItems));
                lvItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (builder.onTextItemClickListener != null) {
                            builder.onTextItemClickListener.onClick(AlertView.this, position);
                        }
                        dismiss();
                    }
                });
            } else {
                lvItems.setAdapter(builder.listAdapter);
                lvItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (builder.onTextItemClickListener != null) {
                            builder.onTextItemClickListener.onClick(AlertView.this, position);
                        }
                    }
                });
            }

        }
        //单选列表
        else if (builder.itemsType == ItemsType.SingleChoice) {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) llRoot.getLayoutParams();
            params.width = RelativeLayout.LayoutParams.MATCH_PARENT;
            llRoot.setLayoutParams(params);

            lvItems.setVisibility(View.VISIBLE);
            lvItems.setAdapter(new ArrayAdapter<>(getContext(),
                    R.layout.list_item_single_choice,
                    builder.textItems));
            lvItems.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
            lvItems.setItemChecked(builder.checkedItem, true);
            lvItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (builder.onTextItemClickListener != null) {
                        builder.onTextItemClickListener.onClick(AlertView.this, position);
                    }
                }
            });
        }
        //多选列表
        else if (builder.itemsType == ItemsType.MultiChoice) {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) llRoot.getLayoutParams();
            params.width = RelativeLayout.LayoutParams.MATCH_PARENT;
            llRoot.setLayoutParams(params);

            lvItems.setVisibility(View.VISIBLE);
            lvItems.setAdapter(new ArrayAdapter<>(getContext(),
                    R.layout.list_item_multi_choice,
                    builder.textItems));
            lvItems.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);

            for (int i = 0; i < builder.checkedItems.length; i++) {
                if (builder.checkedItems[i]) {
                    lvItems.setItemChecked(i, true);
                }
            }
            lvItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (builder.onMultiChoiceClickListener != null) {
                        boolean isChecked = lvItems.getCheckedItemPositions().get(position);
                        builder.onMultiChoiceClickListener.onClick(AlertView.this, position, isChecked);
                    }
                }
            });
        }
        //普通提示信息
        else if (!TextUtils.isEmpty(message)) {
            tvMessage.setVisibility(View.VISIBLE);
            tvMessage.setText(message);
            tvMessage.setGravity(builder.msgGravity);
            if (builder.msgColor != -1) {
                tvMessage.setTextColor(builder.msgColor);
            }
            if (builder.msgSize != -1) {
                tvMessage.setTextSize(builder.msgSize);
            }
        }

        //判断有没有底部按钮
        if (TextUtils.isEmpty(confirmTxt) && TextUtils.isEmpty(cancelTxt)) {
            llBottomBtn.setVisibility(View.GONE);
            bottomDivider.setVisibility(View.GONE);
        }

        if (builder.cancelTextColor != -1) {
            btnCancel.setTextColor(builder.cancelTextColor);
        }


        //判断有没有确定按钮
        if (TextUtils.isEmpty(confirmTxt)) {
            btnConfirm.setVisibility(View.GONE);
            centerDivider.setVisibility(View.GONE);
        } else {
            btnConfirm.setText(confirmTxt);
            btnConfirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (confirmListener != null) {
                        confirmListener.onClick(AlertView.this, 0);
                    }
                    dismiss();
                }
            });

            if (builder.confirmTextColor != -1) {
                btnConfirm.setTextColor(builder.confirmTextColor);
            }
        }

        //判断有没有取消按钮
        if (TextUtils.isEmpty(cancelTxt)) {
            btnCancel.setVisibility(View.GONE);
            centerDivider.setVisibility(View.GONE);
        } else {
            btnCancel.setText(cancelTxt);
            btnCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (cancelListener != null) {
                        cancelListener.onClick(AlertView.this, 0);
                    }
                    dismiss();
                }
            });
        }
        //设置是否可以取消
        setCancelable(builder.mCancelable);
        //设置是否可以点击外部取消
        setCanceledOnTouchOutside(builder.mCanceledOnTouchOutside);


    }

    //初始化底部弹框
    private void initSheetView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);

        tvMessage = (TextView) findViewById(R.id.tv_message);
        lvItems = (ListView) findViewById(R.id.lv_alert_list);

        sheetCancel = (TextView) findViewById(R.id.tv_alert_cancel);


        //判断是否显示标题
        if (TextUtils.isEmpty(builder.mTitle)) {
            tvTitle.setVisibility(View.GONE);
        } else {
            tvTitle.setVisibility(View.VISIBLE);
            tvTitle.setText(builder.mTitle);
        }

        //判断是否显示内容
        if (TextUtils.isEmpty(builder.mMessage)) {
            tvMessage.setVisibility(View.GONE);
        } else {
            tvMessage.setVisibility(View.VISIBLE);
            tvMessage.setText(message);
            tvMessage.setGravity(builder.msgGravity);
            if (builder.msgColor != -1) {
                tvMessage.setTextColor(builder.msgColor);
            }
            if (builder.msgSize != -1) {
                tvMessage.setTextSize(builder.msgSize);
            }
        }

        //设置底部按钮文字
        if (TextUtils.isEmpty(builder.mCancelText)) {
            sheetCancel.setText("取消");
        } else {
            sheetCancel.setText(builder.mCancelText);
        }
        //设置底部监听
        sheetCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (builder.onCancelListener != null) {
                    builder.onCancelListener.onClick(AlertView.this, 0);
                }
                dismiss();
            }
        });

        //设置数据
        final List<String> data = new ArrayList<>();
        data.addAll(Arrays.asList(builder.actions));

        final Set<Integer> highLightSet = new HashSet<>();
        for (int i = 0; i < builder.highLightPositions.length; i++) {
            highLightSet.add(builder.highLightPositions[i]);
        }
        lvItems.setAdapter(new BaseAdapter<String>(getContext(), data) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if (convertView == null) {
                    convertView = inflate(R.layout.list_item_sheet);
                }

                TextView tvAlert = ViewHolder.get(convertView, R.id.tv_alert_item);
                View divider = ViewHolder.get(convertView, R.id.view_alert_divider);

                if (position == 0 && TextUtils.isEmpty(builder.mTitle)) {
                    divider.setVisibility(View.GONE);
                } else {
                    divider.setVisibility( View.VISIBLE);
                }

                String data = getItem(position);
                tvAlert.setText(data);
                //设置高亮
                if (highLightSet.contains(position)) {
                    tvAlert.setTextColor(getContext().getResources().getColor(R.color.red_dark));
                } else {
                    tvAlert.setTextColor(getContext().getResources().getColor(R.color.meta_text_primary));
                }
                return convertView;
            }
        });
        lvItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (builder.onTextItemClickListener != null) {
                    builder.onTextItemClickListener.onClick(AlertView.this, position);
                }
                dismiss();
            }
        });
        //设置是否可以取消
        setCancelable(builder.mCancelable);
        //设置是否可以点击外部取消
        setCanceledOnTouchOutside(builder.mCanceledOnTouchOutside);
    }


    public TextView getMessageView() {
        return tvMessage;
    }


    public static class Builder {

        private Style alertStyle;

        private String mTitle;
        private String mMessage;
        private String mConfirmText;
        private String mCancelText;
        private Context mContext;

        private int msgGravity = Gravity.LEFT;
        private int msgColor = -1;
        private float msgSize = -1;

        private boolean mCancelable = true;
        private boolean mCanceledOnTouchOutside = true;

        private OnClickListener onConfirmListener;
        private OnClickListener onCancelListener;

        private int confirmTextColor = -1;
        private int cancelTextColor = -1;

        private ItemsType itemsType = ItemsType.Null;
        private String[] textItems;
        private ListAdapter listAdapter;

        private int checkedItem;
        private boolean[] checkedItems;
        private OnClickListener onTextItemClickListener;
        private OnMultiChoiceClickListener onMultiChoiceClickListener;

        private String[] actions;
        private int[] highLightPositions;


        public Builder(Context context) {
            this(context, Style.Dialog);
        }

        public Builder(Context context, Style style) {
            this.mContext = context;
            this.alertStyle = style;
        }

        public Builder setTitle(String title) {
            mTitle = title;
            return this;
        }

        public Builder setMessage(String message) {
            mMessage = message;
            return this;
        }

        public Builder setMessageGravity(int gravity) {
            msgGravity = gravity;
            return this;
        }

        public Builder setMessageColor(int color) {
            msgColor = color;
            return this;
        }

        public Builder setMessageSize(int size) {
            msgSize = size;
            return this;
        }

        public Builder setConfirmButton(String confirmTxt, OnClickListener listener) {
            mConfirmText = confirmTxt;
            onConfirmListener = listener;
            return this;
        }

        public Builder setCancelButton(String cancelText, OnClickListener listener) {
            mCancelText = cancelText;
            onCancelListener = listener;
            return this;
        }

        public Builder setConfirmTextColor(int color) {
            confirmTextColor = color;
            return this;
        }

        public Builder setCancelTextColor(int color) {
            cancelTextColor = color;
            return this;
        }


        public Builder setCancelable(boolean cancelable) {
            mCancelable = cancelable;
            return this;
        }

        public Builder setCanceledOnTouchOutside(boolean flag) {
            mCanceledOnTouchOutside = flag;
            return this;
        }

        public Builder setItems(String[] array, OnClickListener clickListener) {
            textItems = array;
            onTextItemClickListener = clickListener;
            itemsType = ItemsType.Items;
            return this;
        }

        public Builder setSingleChoiceItems(String[] array, int checkedItem,
                                            OnClickListener clickListener) {
            textItems = array;
            this.checkedItem = checkedItem;
            onTextItemClickListener = clickListener;
            itemsType = ItemsType.SingleChoice;
            return this;
        }

        public Builder setMultiChoiceItems(String[] items, boolean[] checkedItems,
                                                   OnMultiChoiceClickListener listener) {
            textItems = items;
            onMultiChoiceClickListener = listener;
            this.checkedItems = checkedItems;
            itemsType = ItemsType.MultiChoice;
            return this;
        }

        public Builder setItems(ListAdapter adapter, OnClickListener clickListener) {
            listAdapter = adapter;
            itemsType = ItemsType.Items;
            return this;
        }

        public Builder setActionSheet(String[] actions,
                                      OnClickListener clickListener) {
            setActionSheet(actions, new int[0], clickListener);
            return this;
        }

        public Builder setActionSheet(String[] actions,
                                      int[] highLightPositions,
                                      OnClickListener clickListener) {
            this.actions = actions;
            this.highLightPositions = highLightPositions;
            onTextItemClickListener = clickListener;
            msgGravity = Gravity.CENTER;
            return this;
        }


        public AlertView build() {
            AlertView alertDialog = new AlertView(mContext, this);
            return alertDialog;
        }
    }

}
